﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AgencyEntityLib.BaseEntity;
using FormControllers;
using System.Web.Security;
using Ecopsy.DataTier;
using AgencyEntityLib.Context;

public partial class EmplEditor : System.Web.UI.Page
{
    /// <summary>
    /// На основании Текущего UserName - обратиться к базе и вычислить Агенство
    /// </summary>
    /// <returns></returns>
    public  string GetAgencyId()
    {
        return AgencyID;
       
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        AgencyLib_GlobalConstants._getAgencyId = GetAgencyId;
        AgencyEntityLib.Context.AgencyLib_GlobalConstants._getAgencyId = GetAgencyId;
        if (!IsPostBack)
        {
            MyDataBind();
        }
    }

    private void MyDataBind()
    {
        ///chRoleList.DataSource = GetEmplRoles();////Чудо блять!!!
        ListItemCollection coll = GetEmplRoles();
        chRoleList.Items.Clear();
        foreach (ListItem i in coll)
        {
            ListItem it = new ListItem(i.Text, i.Value);
            it.Selected = i.Selected;
            chRoleList.Items.Add(it);
        }
        DataBind();
    }
    protected Employeer Employeer
    {
        get { return GetEmpl(ID) ; }
    }
    protected void btnsave_Click(object sender, EventArgs e)
    {

        List <String> err= new List<string> ();
        CreateUser(err);
        if (err.Count > 0) {ListBox1.DataSource = err; ListBox1.DataBind();}
        Employeer.FirstName = txtFirstName.Text;
        Employeer.SecondName  = txtSecondName.Text;
        Employeer.LastName = txtLastName.Text;
        Employeer.Login = txtLogin.Text;
        Employeer.eMail = txtEmail.Text;
        Employeer.Describe = txtComment.Text;
        
        System.Web.Security.MembershipUser usr = System.Web.Security.Membership.GetUser(Employeer.Login);
        SetRoles(usr);

        Employeer.Save();  
    }

    private string ID { get { return Request.QueryString["ID"]; } }
    private string AgencyID { get { return Request.QueryString["AgencyID"]; } }
    public Employeer GetEmpl(string ID)
    {
        if (!CacheTools.IsCacheObject(ID))
        {
            Employeer p = new Employeer();
            p.ID = ID;
            p.Load();
            CacheTools.SetCacheObject(ID, p);
            return p;
        }

        return (Employeer)CacheTools.GetCacheObect(ID);

    }

    private string DepartmentID
    {
        get { return Request.QueryString["DepartmentID"]; }
    }

    protected void ReturnButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("EmplList.aspx?DepartmentID=" + DepartmentID + "&AgencyID=" + AgencyID);
    }

    private MembershipUser CreateUser(List<string> ErrList)
    {
        if (txtPassword.Text != txtconfirm.Text) throw new Exception("Подтвердите пароль.");
        MembershipUser usr = null;
        try
        {
            if (string.Empty != Employeer.Login) Membership.DeleteUser(txtLogin.Text);

            usr = Membership.CreateUser(txtLogin.Text, txtPassword.Text);
        }
        catch (Exception exc)
        {
            ErrList.Add(exc.Message);
        }
        return usr;

    }

    private void SetRoles(System.Web.Security.MembershipUser usr)
    {
        foreach (ListItem item in chRoleList.Items)
        {
            System.Web.Security.Roles.RemoveUserFromRole(usr.UserName, item.Value);

            if (item.Selected)
            {
                System.Web.Security.Roles.AddUserToRole(usr.UserName, item.Value);
            }

        }
    }

    private ListItemCollection GetEmplRoles()
    {
        Employeer emp = Employeer;

        ////список ролей        
        RoleList r = GetRoleList();


        RoleMemberList memb = GetRoleMemberList(emp.Login);

        ListItemCollection coll = new ListItemCollection();

        foreach (DictionaryItem item in r)
        {
            ListItem i = new ListItem();
            i.Value = item.ID;
            i.Text = item.Value.ToString();
            i.Selected = (null != memb[item.ID]);
            coll.Add(i);
        }
        return coll;
    }

    public RoleList GetRoleList()
    {
        ////список ролей
        RoleList r = new RoleList();
        r.Load();
        return r;
    }

    public RoleMemberList GetRoleMemberList(string Login)
    {
        ////список ролей в которых учавствует товарищ
        RoleMemberList memb = new RoleMemberList();
        memb.Login = Login;
        memb.Load();
        return memb;

    }

}
